/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pig4cloud.pig.ads.controller;
import javax.annotation.Resource;
import javax.validation.Valid;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.ads.gdt.service.GdtBrandImageService;
import com.pig4cloud.pig.ads.service.AdCreativeComponentService;
import com.pig4cloud.pig.api.dto.*;
import com.pig4cloud.pig.api.entity.*;
import com.pig4cloud.pig.ads.service.TtAdCreativeTempService;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.pig4cloud.pig.ads.service.AdvCreativeService;
import com.pig4cloud.pig.common.core.util.R;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;


/**
 * @ 广告计划管理模块 前端控制器
 * @author hma
 *
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/creative")
@Api(value = "creative", tags = "广告创意管理模块")
public class AdvCreativeController {
	@Resource
	private AdvCreativeService advCreativeService;

	@Resource
	private AdCreativeComponentService adCreativeComponentService;

	@Autowired
	private TtAdCreativeTempService ttAdCreativeTempService;

	@Resource
	private GdtBrandImageService gdtBrandImageService;

	/**
	 * 分页查询广告计划信息
	 * @param campaignDto 分页对象
	 * @return 分页对象
	 */
	@SysLog("getAdvCreativeStatisticPage")
	@RequestMapping("/getAdvCreativeStatisticPage")
	public R getAdvCreativeStatisticPage(@RequestBody  CampaignDto campaignDto) {
		return  advCreativeService.getAdvCreativeStatistic(campaignDto);
	}

	/**
	 * 修改广告创意状态
	 * @param planDto 修改广告创意状态
	 * @return
	 */
	@SysLog("updateCreativeStatus")
	@RequestMapping("/updateCreativeStatus")
	public R updateCreativeStatus(AdvertiserDto planDto) {
		return  advCreativeService.updateCreativeStatus(planDto);
	}



	//新建

	@RequestMapping("/temp/create")
	public R create(@RequestBody TtAdCreativeTemp record) {
		return ttAdCreativeTempService.create(record);
	}

	//详情
	@RequestMapping("/temp/detail")
	public R detail(Integer id) {
		TtAdCreativeTemp ap = ttAdCreativeTempService.detail(id);
		if (ap != null) {		    
		    return R.ok(ap);
		} else {
		    return R.failed("未找到记录");		    
		}
	}

	//更新
	@RequestMapping("/temp/update")
	public R update(TtAdCreativeTemp record) {
		return ttAdCreativeTempService.update(record);
	}

	//删除
	@RequestMapping("/temp/delete")
	public R delete(Long id) {
		return ttAdCreativeTempService.delete(id);
	}

	@RequestMapping("/temp/latest_record")
	public R detail(Long advertiserId,Long adId,Long id) {
		return ttAdCreativeTempService.latestRecord(advertiserId,adId,id);
	}

	@RequestMapping("/temp/test_create")
	public R create(Long id) {
		TtAdCreativeTemp record = ttAdCreativeTempService.getById(id);
		return R.ok(advCreativeService.createAdvCreative(record));
	}

	@PostMapping("/component/create")
	public R component4Create(@RequestBody @Valid CreativeComponentDto dto) {
		return adCreativeComponentService.component4Create(dto);
	}

	@PostMapping("/component/edit")
	public R component4Edit(@RequestBody @Valid CreativeComponentDto dto) {
		if (dto.getComponent_id() == null) {
			return R.failed("组件ID不能为空");
		}
		return adCreativeComponentService.component4Edit(dto);
	}

	@GetMapping("/component/list")
	public R getComponentList(Page page, CreativeComponentSearchDto dto) {
		LambdaQueryWrapper<AdCreativeComponent> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(AdCreativeComponent::getIsDeleted, 0));
		query.and(wrapper -> wrapper.eq(AdCreativeComponent::getAdvertiserId, dto.getAdvertiser_id()));
		query.and(StringUtils.isNotBlank(dto.getComponent_name()),wrapper -> wrapper.like(AdCreativeComponent::getComponentName, dto.getComponent_name())
									.or().eq(AdCreativeComponent::getComponentId,dto.getComponent_name()));
		//默认不查询审核不通过的
		query.and(wrapper -> wrapper.in(AdCreativeComponent::getStatus, Lists.newArrayList("PASS","UNDER")));
		query.and(StringUtils.isNotBlank(dto.getStatus()),wrapper -> wrapper.eq(AdCreativeComponent::getStatus,dto.getStatus()));

		//根据创建时间倒序
		query.orderByDesc(AdCreativeComponent::getThirdCreateTime);
		IPage<AdCreativeComponent> listPage = adCreativeComponentService.page(page, query);
		if (CollectionUtils.isNotEmpty(listPage.getRecords())) {
			listPage.getRecords().forEach(component -> {
				JSONObject data = JSON.parseObject(component.getComponentData());
				JSONArray imageInfoList = data.getJSONArray("image_info");
				if (CollectionUtils.isNotEmpty(imageInfoList)) {
					//推广卡片只有一张图
					JSONObject imageInfo = imageInfoList.getJSONObject(0);
					String imageId = imageInfo.getString("web_uri");
					GdtBrandImage image = gdtBrandImageService.getOne(Wrappers.<GdtBrandImage>lambdaQuery()
							.eq(GdtBrandImage::getIsdelete, 0)
							.eq(GdtBrandImage::getImageId, imageId)
							.eq(GdtBrandImage::getAccountId,component.getAdvertiserId())
							.last("LIMIT 1"));
					if (image != null) {
						component.setImageUrl(image.getImageUrl());
					}
				}
			});
		}
		return R.ok(listPage);
	}

}
